import { Meteor } from 'meteor/meteor';
import { HTTP } from 'meteor/http';
var sha1 = require('sha1');

Meteor.startup(() => {
    // code to run on server at startup
    var AppID = "wxc64b20e2857b02be";
    var AppSecret = "a8ad134ac4f09d7c71a6b25d2126ae86";
    var nonceStr = "huadian";
    Meteor.methods({
        wxApi: (c_url) => {
            //console.log('test ... ');
            //return "SUCCESS";
            const token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + AppID +"&secret=" + AppSecret;
            var result1 = HTTP.get(token_url);
            //console.log(result1.data);
            let access_token = result1.data.access_token;
            const ticket_url = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi`;
            var result2 = HTTP.get(ticket_url);
            //console.log(result2.data);
            const timestamp = (new Date()).valueOf().toString().slice(0, 10);
            let ticket = result2.data.ticket;
            const jsapi_ticket = `jsapi_ticket=${ticket}&noncestr=${nonceStr}&timestamp=${timestamp}&url=${c_url}`;
            //console.log('---');
            //console.log(jsapi_ticket);
            const signature = sha1(jsapi_ticket);
            const re = {
                appId: AppID,
                timestamp: timestamp,
                nonceStr: nonceStr,
                signature: signature,
                jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage']
            };
            //console.log(re);
            return re;
        },
        insert_phone: (args) => {
            console.log(args);
            if(args.current_phone) {
                phone.insert(args);
                return true;
            } else {
                return false;
            }
        }
    })
});
